<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/2/7
 * Time: 13:56
 * Desc: 商品列表服务层
 */
namespace app\index\service;
use think\Controller;
use think\Db;
use app\index\service\WeixinService;
use app\comm\service\DadaOpenapi;


class GoodsListService extends Controller{
    /**
     * @Author  lingyun
     * @Desc    商品列表
     * 2018-03-29
     */
    public function goods_list(){
        $cate = db('goods_category')->where(['is_exp'=>0,'is_deleted'=>0,'status'=>1])->order('dis_order desc')->limit(1)->find();
        $store_id = cookie('store_id');         //当前门店id

        $cate_id = empty(input('cate_id'))?$cate['id']:input('cate_id');            //门店顶级商品分类id
        $exp_cate = input('exp_cate');          //门店商品扩展分类

//        if(empty($cate_id)){                    //当选中分类为空时，使用默认分类
//            $cate = db('goods_category')->where(['is_exp'=>0,'is_deleted'=>0,'status'=>1,'store_id'=>0])->order('dis_order desc')->limit(1)->find();
//            $cate_id = $cate['id'];
//        }

        $category = get_top_category();           //商品顶级分类
        $exp_category = get_exp_category();       //商品扩展分类

        //查询条件
        if(empty($exp_cate)){
            $where_goods_arr = [
                'a.store_id'=>0,
                'a.is_deleted'=>0,
                'a.is_online'=>1,         //恢复线上线下状态 @lingyun  2018-03-29
                'a.status'=>1,
                'a.cat_id'=>$cate_id
            ];
        }else{
            $where_goods_arr = [
                'a.store_id'=>0,
                'a.is_deleted'=>0,
                'a.is_online'=>1,       //恢复线上线下状态 @lingyun  2018-03-29
                'a.status'=>1,
                'a.cat_id'=>$cate_id,
                'a.exp_cat'=>$exp_cate
            ];
        }

        //查询会员等级价格
        $join = [
            ['ys_sys_level b','a.member_level_id=b.id','LEFT']
        ];

        $member = db('user')->where('uid',session('_user_uid_.uid'))->field('uid,nickname,realname,level_id,mobile')->find();
        if(!is_mobile() && !is_weixin()){
            $goods = db('goods')->alias('a')->join($join)->field('a.*,b.title,b.css_color')->where($where_goods_arr)->paginate(8,false,['query'=>request()->param()]);     //商品列表
            $page = $goods->render();               //分页数据
//        $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 5> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 ORDER BY a.id DESC";
//        $tui_goods = Db::query($sql);

            $all_goods = $goods->all();        //取出数据
        }else{
            $goods = db('goods')->alias('a')->join($join)->field('a.*,b.title,b.css_color')->where($where_goods_arr)->paginate(10000,false,['query'=>request()->param()]);     //商品列表
            $page = $goods->render();               //分页数据
//        $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 5> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 ORDER BY a.id DESC";
//        $tui_goods = Db::query($sql);

            $all_goods = $goods->all();        //取出数据
        }


        $this->assign('page',$page);
        $this->assign('goods',$goods);                          //商品列表
        $this->assign('member',$member);                        //会员信息
        $this->assign('category',$category);                    //商品分类导航
        $this->assign('exp_category',$exp_category);            //商品扩展分类
        $this->assign('cate_id',$cate_id);                      //当前商品分类，默认第一个商品分类
        $this->assign('exp_cate',$exp_cate);                    //商品当前扩展分类
        $this->assign('cash_coupon',0);                         //不是代金券
        $this->assign('url',url('GoodsList/goods_list'));       //登录跳转链接
        $this->assign('realname',session('_user_uid_.realname'));
        $this->assign('all_goods',$all_goods);
//        $this->assign('tui_goods',$tui_goods);                  //推荐商品
    }

    /**
     * @Author  lingyun
     * @Desc    会员商品列表
     * 2018-05-18
     */
    public function member_goods_list(){
        $cate = db('goods_category')->where(['is_exp'=>0,'is_deleted'=>0,'status'=>1])->order('dis_order desc')->limit(1)->find();
        $store_id = cookie('store_id');         //当前门店id

        $exp_cate = input('exp_cate');          //门店商品扩展分类
        $category = get_top_category();           //商品顶级分类
        $exp_category = get_exp_category();       //商品扩展分类

        //查询条件
        if(empty($exp_cate)){
            $where_goods_arr = [
                'a.store_id'=>0,
                'a.is_deleted'=>0,
                'a.is_online'=>1,         //恢复线上线下状态 @lingyun  2018-03-29
                'a.status'=>1,
                'a.member_level_id'=>['gt',1]
            ];
        }else{
            $where_goods_arr = [
                'a.store_id'=>0,
                'a.is_deleted'=>0,
                'a.is_online'=>1,       //恢复线上线下状态 @lingyun  2018-03-29
                'a.status'=>1,
                'a.member_level_id'=>['gt',1],
                'a.exp_cat'=>$exp_cate
            ];
        }
        //查询会员等级价格
        $join = [
            ['ys_sys_level b','a.member_level_id=b.id','LEFT']
        ];

        $member = db('user')->where('uid',session('_user_uid_.uid'))->field('uid,nickname,realname,level_id,mobile')->find();
        if(!is_mobile() && !is_weixin()){
            $goods = db('goods')->alias('a')->join($join)->field('a.*,b.title,b.css_color')->where($where_goods_arr)->paginate(8,false,['query'=>request()->param()]);     //商品列表
            $page = $goods->render();               //分页数据

            $all_goods = $goods->all();        //取出数据
        }else{
            $goods = db('goods')->alias('a')->join($join)->field('a.*,b.title,b.css_color')->where($where_goods_arr)->paginate(10000,false,['query'=>request()->param()]);     //商品列表
            $page = $goods->render();               //分页数据

            $all_goods = $goods->all();        //取出数据
        }


        $this->assign('page',$page);
        $this->assign('goods',$goods);                          //商品列表
        $this->assign('member',$member);                        //会员信息
        $this->assign('category',$category);                    //商品分类导航
        $this->assign('exp_category',$exp_category);            //商品扩展分类
        $this->assign('cate_id',99999);                      //当前商品分类，默认第一个商品分类
        $this->assign('exp_cate',$exp_cate);                    //商品当前扩展分类
        $this->assign('cash_coupon',0);                         //不是代金券
        $this->assign('url',url('GoodsList/goods_list'));       //登录跳转链接
        $this->assign('realname',session('_user_uid_.realname'));
        $this->assign('all_goods',$all_goods);
    }

    /**
     * @Author  lingyun
     * @Desc    商品详情
     * 2018-03-29
     */
    public function goods_detail(){
        $id = input('id');                                          //商品id
        $cur_page = empty(input('page'))?1:input('page');           //当前的页码
        $store_id = cookie('store_id');                             //门店id
        $category = get_top_category();                             //获取顶部导航
        $member = db('user')->where('uid',session('_user_uid_.uid'))->find();       //当前登录的会员

        $goods = db('goods')->where('id',$id)->find();              //商品详情
        if(empty($goods) || $goods['status'] == 0 || $goods['is_deleted'] == 1){
            $this->assign('err_msg','找不到该商品，请浏览其它商品');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','浏览其他商品');
            return false;
        }
        $goods['images'] = explode('|',$goods['images']);

        $goods['detail'] = htmlspecialchars_decode($goods['detail']);

        //商品属性主键id   ys_goods_spec_detail => 主键id
        $specs = db('goods_spec_detail')->where(['goods_id'=>$id,'is_deleted'=>0])->column('specs');
        $specs = implode(',',$specs);                                   //169,170,171
        $specs = implode(',',array_unique(explode(',',$specs)));        //将转换的字符串去重

        $spec_result = db('goods_spec')->where('id','in',$specs)->column('id,goods_id,spec_id,detail');
        $spec_id = array_values(array_unique(array_column($spec_result, 'spec_id')));        //取出商品属性id -- 去重 -- 数组
        $spec_id = implode(',',$spec_id);
        //商品属性分类： 尺寸、温度
        $spec_name = db('goods_spec_name')->where('id','in',$spec_id)->column('id,name,addtime');

        //判断是否已经收藏了该商品
        $collect = db('user_collect')->where(['uid'=>session('_user_uid_.uid'),'goods_id'=>$goods['id'],'store_id'=>$store_id])->find();

        $comment = db('goods_comment')->alias('a')->join('ys_user b','a.uid=b.uid','LEFT')->where(['a.goods_id'=>$id,'a.is_show'=>1,'a.is_deleted'=>0])->field('a.*,b.mobile,b.logo,b.realname')->paginate(10,false,['query'=>request()->param()]);
        $pinglun = $comment->all();
        $all_comment = db('goods_comment')->where(['goods_id'=>$id,'is_show'=>1,'is_deleted'=>0])->count();
        $all_page = $all_comment/2;
        $page = $comment->render();
        //转化评论图集
        foreach($pinglun as $k=>$v){
            if(!empty($v['images'])){
                $pinglun[$k]['images'] = explode(',',$v['images']);
            }
        }

        if(empty($collect)){
            $this->assign('is_collect',0);
        }else{
            if($collect['status'] == 1){
                $this->assign('is_collect',1);
            }else{
                $this->assign('is_collect',0);
            }
        }

        if(empty($spec_result)){        //无属性商品 -- 直接返回商品id
            $store_goods_id = db('store_goods_stock')->where(['store_id'=>$store_id,'goods_id'=>$id])->value('id');
            $this->assign('store_goods_id',$store_goods_id);
        }else{
            $this->assign('store_goods_id','');
        }

        if(count($spec_name) == 0){     //
            $goods_specs_details = db('goods_spec_detail')->where(['goods_id'=>$goods['id'],'is_deleted'=>0])->find();
            if($goods['member_level_id'] !=1 && $member['level_id'] >= $goods['member_level_id']){
                $goods['price'] = $goods_specs_details['member_price'];
            }else{
                $goods['price'] = $goods_specs_details['price'];        //商品价格
            }
            $goods['stock'] = $goods_specs_details['stock'];
        }

        $this->assign('member',$member);                        //会员信息
        $this->assign('category',$category);                    //顶部导航
        $this->assign('spec_name',$spec_name);                  //属性分类
        $this->assign('spec_result',$spec_result);              //属性明细
        $this->assign('spec_count',count($spec_name));          //商品属性分类的种类
        $this->assign('goods',$goods);
        $this->assign('all_comment',$all_comment);
        $this->assign('pinglun',$pinglun);
        $this->assign('page',$page);
        $this->assign('cur_page',$cur_page);                   //当前的页码
        $this->assign('all_page',ceil($all_page));                   //全部页面
        $this->assign('url',url('GoodsList/goods_detail')."?id=".$id);        //登录跳转回的页面
    }

    /**
     * @Author  lingyun
     * @Desc    计算所选属性的商品价格以及商品库存
     *          根据会员等级进行计算
     * 2018-03-30
     */
    public function pre_calculate_price(){
        $post = input('post.');
        $store_id = cookie('store_id');             //当前的门店信息

        $member = db('user')->where('uid',session('_user_uid_.uid'))->field('uid,realname,mobile,level_id')->find();        //查询会员信息

        if(empty($store_id)){
            $this->error('请先选择门店','');
        }
        $post['specs'] = trim($post['specs'],',');      //商品属性详情

        $goods = db('goods')->where('id',$post['goods_id'])->field('id,member_level_id,addtime')->find();           //查询商品信息，用于判断会员商品

        $goods_spec_detail = db('goods_spec_detail')->where(['goods_id'=>$post['goods_id'],'specs'=>$post['specs'],'is_deleted'=>0])->find();     //商品属性详情

        if(empty($goods_spec_detail)){        //不用判断is_deleted，总部下架该属性，但是门店还有库存，必须继续出售
            $this->error('该商品已下架，请选择其它商品','');         //ajax方式提交
        }else{
            $where = [
                'store_id'=>$store_id,
                'onsale'=>1,                //是否出售
                'goods_spec_id'=>$goods_spec_detail['id'],
                'is_deleted'=>0
            ];

            $goods_stock = db('store_goods_stock')->where($where)->find();        //查询该属性的商品信息
            if(empty($goods_stock)){
                $this->error('该商品已下架，请选择其它商品','');
            }

            if($goods_stock['stock'] <= 0){
                $this->error('该商品库存不足，请选择其它商品');
            }else{
                $arr['id'] = $goods_stock['id'];            //商品属性id
                $arr['stock'] = $goods_stock['stock'];      //商品库存
                if(($goods['member_level_id'] != 1) && ($member['level_id'] >= $goods['member_level_id']) || !empty($member)){         //是会员商品，使用会员价格
                    $arr['price'] = $goods_spec_detail['member_price'];         //会员商品价格
                }else{
                    $arr['price'] = $goods_spec_detail['price'];                //原始价格
                }

                $this->success('成功','',$arr);
            }
        }
    }

    /**
     * @Author  lingyun
     * @Desc    加入购物车
     */
    public function addto_cart(){
        $post = input('post.');     //id-ys_store_goods_stock  gods_ys_id-goods     spec-196,198商品属性组合
        $store_id = cookie('store_id');
        if(empty($store_id)){
            $this->error('请选择门店','');
        }
        $post['specs'] = trim($post['specs'],',');

        if($post['sign'] == 1){     //添加有属性的商品
            //商品属性详情
            $spec_detail = db('goods_spec_detail')->where(['goods_id'=>$post['goods_id'],'specs'=>$post['specs'],'is_deleted'=>0])->find();
        }else{
            //商品属性详情
            $spec_detail = db('goods_spec_detail')->where(['goods_id'=>$post['goods_id'],'is_deleted'=>0])->find();
        }

        if(empty($spec_detail)){
            $this->error('该商品已下架，请选择其它商品');
        }else{
            $where = [
                'store_id'=>$store_id,
                'onsale'=>1,
                'goods_spec_id'=>$spec_detail['id'],
                'is_deleted'=>0
            ];
            //查询门店出售的商品
            $goods = db('store_goods_stock')->where($where)->find();
            if(empty($goods)){
                $this->error('该商品已下架，请选择其它商品','');
            }

            if($goods['stock'] <= 0){
                $this->error('该商品库存不足，请选择其它商品','');
            }else{
                $user_cart = cookie('user_cart');

                $num = $post['num'];
                $data['goods_id'] = $post['goods_id'];                  //ys_goods -> id
                $data['specid'] = $spec_detail['id'];                    //goods_spec_detail -> id
                $data['goods_price'] = $spec_detail['price'];            //商品价格
                $data['goods_sum'] = $num;                              //加入购物车的数量
                $data['selected'] = 1;
                $data['store_id'] = $store_id;
                $data['goods_sum_price'] = $spec_detail['price'];            //属相价格
                $data['store_goods_stock_id'] = $post['id'];  //store_goods_stock  =》  id
                $data['addtime'] = time();
                if(empty($user_cart)){      //不存在cookie中的购物车
                    $user_cart[0] = $data;
                    cookie('user_cart',$user_cart,15552000);
                }else{      //cookie中存在购物车
                    $sign = 0;
                    foreach($user_cart as $k=>$v){
                        if(($v['goods_id'] == $data['goods_id']) && ($v['specid'] == $data['specid']) && ($v['store_id'] == $data['store_id'])){
                            $sign = 1;
                            $user_cart[$k]['goods_price'] = $data['goods_price'];
                            $user_cart[$k]['goods_sum'] = $v['goods_sum'] + $data['goods_sum'];
                            $user_cart[$k]['goods_sum_price'] = $data['goods_sum_price'];
                            $user_cart[$k]['addtime'] = time();
                            break;
                        }
                    }
                    if($sign == 0){
                        array_push($user_cart,$data);
                    }
                    cookie('user_cart',$user_cart,15552000);
                }
                $this->success('加入购物车成功','');
            }
        }
    }

    /**
     * @Author  lingyun
     * @Desc    获取可购买的代金券列表
     */
    public function get_cash_coupon_list(){
        //商品顶级分类
        $category = db('goods_category')->where(['status'=>1,'is_deleted'=>0,'is_exp'=>0])->select();
        //扩展分类
        $exp_category = db('goods_category')->where(['status'=>1,'is_deleted'=>0,'is_exp'=>1])->select();

        if(!empty(session('_user_uid_.uid'))){
            $where_ycard = [
                'uid'=>session('_user_uid_.uid'),
                'store_id'=>cookie('store_id')
            ];
            $coupon_id = db('user_ycard')->where($where_ycard)->column('coupon_id');
        }else{
            $where_ycard = [
                'store_id'=>cookie('store_id')
            ];
            $coupon_id = array();
        }


        if(empty($coupon_id)){
            $where_coupon = [
                'status'=>1,
                'is_deleted'=>0,
                'type'=>2,
                'store_id'=>cookie('store_id'),
                'use_end_time'=>['gt',time()]
            ];
        }else{
            $coupon_id = implode(',',$coupon_id);
            $where_coupon = [
                'status'=>1,
                'is_deleted'=>0,
                'type'=>2,
                'id'=>['not in',$coupon_id],
                'store_id'=>cookie('store_id'),
                'use_end_time'=>['gt',time()]
            ];
        }

        $goods = db('store_coupon')->where($where_coupon)->field('*,img as logo,1 as member_level_id,"普通会员" as title,price as member_price ')->paginate(8,false,['query'=>request()->param()]);

        //分页数据
        $page = $goods->render();
        $all_goods = $goods->all();

        $this->assign('page',$page);
        $this->assign('goods',$goods);
        $this->assign('category',$category);
        $this->assign('exp_category',$exp_category);
        $this->assign('cate_id',0);
        $this->assign('exp_cate',0);
        $this->assign('city',cookie('city'));
        $this->assign('all_goods',$all_goods);
        $this->assign('cash_coupon',1);     //不是代金券
        $this->assign('url',url('Index/index'));     //不是代金券
    }

    /**
     * @Author  lingyun
     * @Desc    代金券详情信息
     * 2018-05-04
     */
    public function get_cash_coupon_detail(){
        $id = input('id');                                          //商品id
        $store_id = cookie('store_id');                             //门店id
        $store = db('store')->where('id',$store_id)->find();        //门店信息
        $category = get_top_category();                             //获取顶部导航
        $member = db('user')->where('uid',session('_user_uid_.uid'))->find();       //当前登录的会员
        $coupon = db('store_coupon')->where('id',$id)->find();

        if(isMobile()){
            if(is_weixin()){
                $this->assign('is_mobile',0);
            }else{
                $this->assign('is_mobile',1);
            }
        }else{
            $this->assign('is_mobile',0);
        }
        $this->assign('member',$member);                        //会员信息
        $this->assign('category',$category);                   //顶部导航
        $this->assign('coupon',$coupon);                   //顶部导航
        $this->assign('store',$store);                   //门店信息
        $this->assign('url',url('GoodsList/cash_coupon_detail')."?id=".$id);        //登录跳转回的页面

    }

    /**
     * @Author  lingyun
     * @Desc    创建代金券订单
     * 2018-05-04
     */
    public function create_cash_coupon_order(){
        $id = input('id');
        $category = get_top_category();                             //获取顶部导航
        $member = db('user')->where('uid',session('_user_uid_.uid'))->find();       //当前登录的会员
        $coupon = db('store_coupon')->where('id',$id)->find();

        if(isMobile()){
            if(is_weixin()){
                $this->assign('is_mobile',0);
            }else{
                $this->assign('is_mobile',1);
            }
        }else{
            $this->assign('is_mobile',0);
        }
        if(is_weixin()){
            $this->assign('is_weixin',1);
        }else{
            $this->assign('is_weixin',0);
        }

        $this->assign('member',$member);                        //会员信息
        $this->assign('category',$category);                   //顶部导航
        $this->assign('coupon',$coupon);                   //顶部导航
        $this->assign('nowtime',time());                   //顶部导航
        $this->assign('order_sn',create_order_sn(session("_user_uid_.uid")));      //订单编号
        $this->assign('url',url('GoodsList/cash_coupon_detail')."?id=".$id);        //登录跳转回的页面
    }


    /**
     * @Author  lingyun
     * @Desc    使用余额支付代金券
     */
    public function pay_cash_coupon_crdeit($id){
        $uid = session('_user_uid_.uid');
        $member = db('user')->where('uid',$uid)->find();        //会员信息
        $coupon = db('store_coupon')->where('id',$id)->find();
        $data_arr = [
            'order_sn'=>create_order_sn($uid),
            'uid'=>$uid,
            'cat_id'=>$coupon['cat_id'],            //代金券的类型，0通用型
            'cash_coupon_id'=>$id,
            'store_id'=>session('store_id'),
            'pay_time'=>time(),
            'pay_type'=>3,
            'price'=>$coupon['price'],
            'pay_time'=>time(),
            'pay_status'=>1,
            'remark'=>'待支付',
            'addtime'=>time()
        ];
        //插入支付订单
        $order_id = db('cash_coupon_list')->insertGetId($data_arr);      //新增

        $user_ycard_arr = [
            'store_id'=>session('store_id'),
            'uid'=>session('_user_uid_.uid'),
            'coupon_id'=>$coupon['id'],
            'type'=>2,
            'cat_id'=>$coupon['cat_id'],
            'condition'=>$coupon['condition'],
            'morethan'=>$coupon['morethan'],
            'reduce'=>$coupon['reduce'],
            'use_start_time'=>$coupon['use_start_time'],
            'use_end_time'=>$coupon['use_end_time'],
            'addtime'=>time(),
            'price'=>$coupon['price'],
            'value'=>$coupon['value'],
            'is_used'=>0,
            'status'=>1
        ];
        //新增会员优惠券记录
        $res = db('user_ycard')->insertGetId($user_ycard_arr);
        db('user')->where('uid',session('_user_uid_.uid'))->setDec('user_money',$coupon['price']);          //更新会员的余额

        $data_arr1 = [
            'uid'=>$member['uid'],
            'store_id'=>$coupon['store_id'],
            'order_id'=>$order_id,
            'order_sn'=>$data_arr['order_sn'],
            'pay_time'=>time(),
            'pay_status'=>1,
            'pay_type'=>3,
            'amount'=>$coupon['price'],
            'cur_amount'=>$member['user_money'] - $coupon['price'],
            'sign'=>2,
            'chargetype'=>4,        //购买代金券
            'charge_cn'=>'购买代金券，订单号'.$data_arr['order_sn'].'，总价：'.$coupon['price'],
            'addtime'=>time()
        ];
        db('user_wallet_log')->insert($data_arr1);

        //变更门店金额   --  记录数据
        $store = db('store')->where('id',$coupon['store_id'])->find();
        $store_credit_log = [
            'store_id'=>$store['id'],
            'order_id'=>$order_id,
            'type'=>1,
            'credit'=>$coupon['price'],
            'cur_credit'=>$store['total_amount']+$coupon['price'],
            'remark'=>'销售代金券收入',
            'addtime'=>time(),
            'order_type'=>2,
            'order_sn'=>$data_arr['order_sn'],
            'pay_type'=>3,
        ];
        db('store_credit_log')->insert($store_credit_log);
        $store_credit_arr = [
            'total_amount'=>$store['total_amount']+$coupon['price'],
            'credit'=>$store['credit']+$coupon['price'],
            'user_money'=>$store['user_money']+$coupon['price']
        ];
        db('store')->where('id',$store['id'])->update($store_credit_arr);
        //变更门店金额   --  记录数据

//        $where_point_rule['id'] = ['eq',2];
//        $point_rule = db('sys_point')->where($where_point_rule)->find();
//        //变更的积分
//        $point = ceil($coupon['price']/10)*$point_rule['point'];
//        $data_arr2 = [
//            'uid'=>session('_user_uid_.uid'),
//            'store_id'=>session('store_id'),
//            'uidtype'=>1,
//            'signid'=>2,
//            'type'=>1,
//            'point'=>$point,
//            'curpoint'=>$member['pay_points']+$point,
//            'type_cn'=>'购买代金券赠送积分',
//            'remark'=>'购买代金券赠送积分',
//            'addtime'=>time(),
//        ];
//        db('user_point_log')->data($data_arr2)->insert();
//        $cur_level_point = $member['level_point']+$point;
//        $cur_pay_point = $member['pay_points']+$point;
//        $point_rule = db('sys_level')->select();
//        $level = userLevel($point_rule,$cur_level_point);
//        $data_arr3 = [
//            'uid'=>$member['uid'],
//            'user_money'=>$member['user_money']-$coupon['price'],
//            'level_point'=>$cur_level_point,
//            'pay_points'=>$cur_pay_point,
//            'level_id'=>$level
//        ];
//        db('user')->data($data_arr3)->update();
        //支付记录
        $data_arr4 = [
            'order_id'=>$order_id,
            'order_sn'=>$data_arr['order_sn'],
            'order_type'=>1,
            'uid'=>$uid,
            'pay_type'=>3,
            'pay_sign'=>3,
            'store_id'=>$coupon['store_id'],
            'amount'=>$coupon['price'],
            'addtime'=>time(),
            'remark'=>'购买代金券，订单号'.$data_arr['order_sn'].'，总价：'.$coupon['price'],
        ];
        db('pay_log')->data($data_arr4)->insert();      //支付记录


        //支付回调进行三级分销积分变更
//        third_tier_distribution($uid,$coupon['price'],$coupon['store_id'],0,$member['user_money']-$coupon['price']);      //取消赠送积分

        if(!empty($member['openid'])){
            $root = request()->domain();
            //推送模板消息
            $array = [
                "type"   	  =>1,
                "touser" 	  =>$member["openid"],
                "template_id"=>config("weixin_mu_msg.order_status")["tempid"],
                "url" 		  =>$root.'/index.php/index/user/my_coupon',
                "topcolor"  =>"#743A3A",
                "data"   =>[
                    "first" 	    =>["value"=>'订单支付成功', "color"=>"#743A3A"],
                    "keyword1"		=>["value"=>$coupon['price'], 		"color"=>"#743A3A"],
                    "keyword2"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                    "keyword3"		=>["value"=>'支付成功',"color"=>"#743A3A"],
                    "remark"		=>["value"=>"订单支付成功，请到优惠券中心查看", 			"color"=>"#743A3A"],
                ]
            ];
            $this->sendMessage($array);
        }
        $this->redirect('User/my_coupon');
//        $this->success('支付成功',url('User/index'));
    }

    /**
     * @Author lignyun
     * @Desc    推送模板消息
     */
    private function sendMessage($array){
        $wein = new WeixinService();
        $rest  = $wein->sendmsg($array);
    }

    /**
     * @Author  lingyun
     * @Desc    商品评论ajax分页
     * @param $page 当前亚麻
     * @param $goods_id 商品ID
     */
    public function get_ajax_comment($page,$goods_id){
        $page = $page+1;
        $result = db('goods_comment')->alias('a')->join('ys_user b','a.uid=b.uid','LEFT')->where(['a.goods_id'=>$goods_id,'a.is_show'=>1,'a.is_deleted'=>0])->field('a.*,b.realname,b.logo,FROM_UNIXTIME(a.addtime,"%Y-%m-%d" ) as add_time')->page($page,2)->select();
        if(empty($result)){     //到底了
            $this->success($page-1,'',$result);
        }
        foreach($result as $k => $v){
            if(!empty($v['images'])){
                $result[$k]['images'] = explode(',',$v['images']);
            }
        }
        $this->success($page,'',$result);
    }

    /**
     * @Author  lingyun
     * @Desc    检查订单信息是否正确
     * @Param   $param   订单信息
     * 2018-04-26
     */
    public function check_pay_order($param){
        $uid = session('_user_uid_.uid');           //会员主键id

        if(empty($uid)){
            $this->redirect('Login/loginin');
        }

        if($param['goods_id'] == '' ||$param['store_goods_stock_id'] == '' || $param['spec_id'] == ''){
            return ['code'=>'0','error_msg'=>'','err_url'=>url('GoodsList/goods_detail',array('id'=>$param['goods_id'])),'err_button'=>'重新下单'];
        }

        //商品信息
        $goods = db('store_goods_stock')->alias('a')->join('ys_goods_spec_detail b','a.goods_spec_id=b.id','LEFT')->join('ys_goods c','a.goods_id=c.id','LEFT')->field('a.stock,a.is_deleted as deleted_1,a.onsale,b.is_deleted as deleted_2,b.price,b.member_price,c.status,c.is_deleted as deleted_3,c.member_level_id,a.chengben,a.chengben_price,b.peifang_ids')->where('a.id',$param['store_goods_stock_id'])->find();

        if($goods['stock'] < $param['goods_num']){
            return ['code'=>'0','error_msg'=>'商品库存不足，请重新下单','err_url'=>url('GoodsList/goods_detail',array('id'=>$param['goods_id'])),'err_button'=>'重新下单'];
        }

        //查询商品成本
        $chengben_result = $this->get_chengben($goods['peifang_ids'],$goods['chengben'],$goods['chengben_price']);

        $goods['chengben'] = $param['goods_num']*$chengben_result['chengben'];
        $goods['chengben_price'] = $param['goods_num']*$chengben_result['chengben_price'];


        if($goods['deleted_2'] == 1 || $goods['deleted_2'] == 1 || $goods['deleted_3'] == 1 || $goods['onsale'] == 0 || $goods['status'] == 0){
            return ['code'=>'0','error_msg'=>'该商品已下架，请选择其它商品','err_url'=>url('GoodsList/goods_list'),'err_button'=>'浏览其他商品'];
        }

        if(!empty($param['coupon_id'])){
            $coupon = db('user_ycard')->where('id',$param['coupon_id'])->find();
            if($coupon['use_start_time']<time() && $coupon['use_end_time']>time() && $coupon['is_used'] == 0){
                $coupon_price = $coupon['reduce'];
                $param['coupon_price'] = $coupon_price;
            }else{
                $param['coupon_id'] - 0;
                $coupon_price = 0;
                $param['coupon_price'] = 0;
            }
        }else{
            $coupon_price = 0;
            $param['coupon_id'] - 0;
            $param['coupon_price'] = 0;
        }

        if(!empty($param['cash_coupon_id'])){
            $cash_coupon = db('user_ycard')->where('id',$param['cash_coupon_id'])->find();
//            var_dump($cash_coupon['user_start_time']);
//            var_dump($cash_coupon['use_end_time']);
//            var_dump($cash_coupon['is_used']);exit();
            if($cash_coupon['use_start_time']<time() && $cash_coupon['use_end_time']>time() && $cash_coupon['is_used'] == 0){
                $cash_coupon_price = $cash_coupon['value'];
                $param['cash_coupon_price'] = $cash_coupon_price;
            }else{
                $cash_coupon_price = 0;
                $param['cash_coupon_id'] = 0;
                $param['cash_coupon_price'] = 0;
            }
        }else{
            $cash_coupon_price = 0;
            $param['cash_coupon_id'] = 0;
            $param['cash_coupon_price'] = 0;
        }
        //验证收货地址是否正确
        $address = db('user_address')->where('id',$param['address_id'])->find();
        if($param['is_ziqu'] == 0){
            if(!empty($address)){
//            $this->assign('error_msg','收货地址有误，请重新下单');
//            $this->assign('err_url',url('GoodsList/goods_detail',array('id'=>$param['goods_id'])));
//            $this->assign('err_button','重新下单');
//            return $this->fetch('public/error');

                $yunfei = $this->count_delivery_fee($address['address']);        //运费
                if($yunfei['code'] == 0){
//                $this->assign('error_msg','收货地址有误，请重新下单');
//                $this->assign('err_url',url('GoodsList/goods_detail',array('id'=>$param['goods_id'])));
//                $this->assign('err_button','重新下单');
//                return $this->fetch('public/error');

                    return ['code'=>'0','error_msg'=>$yunfei['msg'],'err_url'=>url('GoodsList/goods_detail',array('id'=>$param['goods_id'])),'err_button'=>'重新下单'];

                }else{
//                $delivery_fee = $result['msg'];
                    $param['shipping_price'] = $yunfei['msg'];
                    $address_id = $address['id'];
                }
            }else{
                return ['code'=>'0','error_msg'=>'收货地址有误，请重新下单','err_url'=>url('GoodsList/goods_detail',array('id'=>$param['goods_id'])),'err_button'=>'重新下单'];
            }
        }


        $member = db('user')->where('uid',$uid)->field('uid,level_id,status')->find();        //会员信息
        //2018-05-17 修改
//        if($member['level_id']>=$goods['member_level_id'] && $member['level_id'] != 1){
//            $goods_signal_price = $goods['member_price'];
//            $param['spec_price'] = $goods_signal_price;
//        }else{
//            $goods_signal_price = $goods['price'];
//            $param['spec_price'] = $goods_signal_price;
//        }
        //2018-05-17  修改
        if($member['level_id']>=$goods['member_level_id'] && $goods['member_level_id'] != 1){
            $goods_signal_price = $goods['member_price'];
            $param['spec_price'] = $goods_signal_price;
        }else{
            $goods_signal_price = $goods['price'];
            $param['spec_price'] = $goods_signal_price;
        }


        $param['total_amount'] = $goods_signal_price*$param['goods_num'];
        $param['final_amount'] = $goods_signal_price*$param['goods_num']+$param['shipping_price']-$param['cash_coupon_price']-$param['coupon_price'];

        $order_sn = create_order_sn($uid);      //订单编号

        if($param['is_ziqu'] == 1){         //自取订单
            $param['final_amount'] = $param['final_amount']-$param['shipping_price'];
            $param['shipping_price'] = 0;
        }

        //构造总订单入库信息  order
        $order_data_arr = [
            'uid'=>$uid,
            'coupon_id'=>$param['coupon_id'],
            'coupon_price'=>$param['coupon_price'],
            'cash_coupon_id'=>$param['cash_coupon_id'],
            'cash_coupon_price'=>$param['cash_coupon_price'],
            'order_type'=>1,
            'order_sn'=>$order_sn,
            'store_id'=>cookie('store_id'),
            'order_status'=>0,
            'shipping_status'=>0,
//            'delivery_time'=>$post['delivery_time_1']."-".$post['delivery_time_2'],
            'consignee'=>$address['consignee'],
            'country'=>$address['country'],
            'province'=>$address['province'],
            'city'=>$address['city'],
            'district'=>$address['area'],
            'twon'=>$address['twon'],
            'address'=>$address['address'],
            'zipcode'=>$address['zipcode'],
            'mobile'=>$address['mobile'],
            'email'=>$address['email'],
            'receiver_lng'=>$address['lng'],        //收货人的经度
            'receiver_lat'=>$address['lat'],        //收货人的纬度
            'pay_type'=>$param['pay_type'],
            'pay_status'=>0,
            'goods_num'=>$param['goods_num'],
            'goods_price'=>$param['total_amount'],
            'shipping_price'=>$param['shipping_price'],
            'order_amount'=>$param['final_amount'],
            'final_amount'=>$param['final_amount'],
            'addtime'=>time(),
            'user_note'=>$param['user_note'],
            'score'=>floor($param['final_amount']/3),
            'is_deleted'=>0,
            'address_id'=>$address['id'],
            'chengben'=>$goods['chengben'],
            'chengben_price'=>$goods['chengben_price'],
            'is_ziqu'=>$param['is_ziqu'],
            'pay_type_two'=>0
        ];

        $order_id = db('order')->insertGetId($order_data_arr);       //订单入库
        $spec = db('goods_spec_detail')->where('id',$param['spec_id'])->find();      //商品属性相关内容
        //订单详情入库数据
        $order_detail_data_arr = [
            'uid'=>$uid,
            'order_id'=>$order_id,
            'spec_id'=>$param['spec_id'],
            'spec_detail'=>$spec['title'],
            'goods_id'=>$param['goods_id'],
            'goods_num'=>$param['goods_num'],
            'spec_price'=>$param['spec_price'],         //会员价格
            'discount_signal_price'=>$param['spec_price']-($param['coupon_price']+$param['cash_coupon_price'])/$param['goods_num'],
            'all_discount_prcie'=>$param['spec_price']-($param['coupon_price']+$param['cash_coupon_price'])/$param['goods_num'],
            'final_amount'=>($param['spec_price']-($param['coupon_price']+$param['cash_coupon_price'])/$param['goods_num'])*$param['goods_num'],
            'status'=>0,
            'storeid'=>cookie('store_id'),
            'is_online'=>1,
            'addtime'=>time(),
            'chengben'=>$goods['chengben'],
            'chengben_price'=>$goods['chengben_price'],
            'store_goods_stock_id'=>$param['store_goods_stock_id']
        ];
        $res = db('order_details')->data($order_detail_data_arr)->insert();     //订单详情入库信息
        //订单动作记录入库状态
        $order_action_arr = [
            'uid'=>$uid,
            'order_id'=>$order_id,
            'action_user'=>0,
            'order_status'=>0,
            'pay_status'=>0,
            'status_desc'=>'订单待支付',
            'storeid'=>cookie('store_id'),
            'addtime'=>time()
        ];
        $res = db('order_action')->data($order_action_arr)->insert();           //订单动作详情记录

        //可以领取的优惠券列表 -- srart   移到此处防止会员直接访问链接多次领取
        $time = time();
        $sql = "select a.*,ifnull(b.coupon_id,0) as is_received from ys_store_coupon as a left join (select coupon_id,store_id,uid from ys_user_ycard where uid=".$uid." and store_id=".cookie('store_id').") as b on a.id=b.coupon_id where a.store_id=".cookie('store_id')." and a.condition<=".$param['final_amount']." and a.send_start_time<".$time." and a.send_end_time>".$time." and a.is_deleted=0 and a.type=0 and a.status=1 and a.create_num>a.send_num";
        $receive_coupon = Db::query($sql);
        $total = count($receive_coupon);
        $receive_coupon_id = '';         //可以领取的优惠券id
        foreach($receive_coupon as $k => $v){
            if($v['is_received'] == 0){
                $receive_coupon_id .= $v['id'].",";
            }
        }
        db('order')->where('order_sn',$order_sn)->update(['receive_coupon_id'=>$receive_coupon_id]);        //更新可以领取的优惠券id
        //可以领取的优惠券列表 -- end   移到此处防止会员直接访问链接多次领取

        return ['code'=>1,'order_id'=>$order_id,'order_sn'=>$order_sn,'final_amount'=>$param['final_amount']];
    }


    /**
     * @Author  lingyun
     * @Desc    计算商品成本
     * @param $peifang_ids  配方id
     * @param $chengben 成本
     * @param $chengben_price   成本价
     * @return array
     */
    private function get_chengben($peifang_ids,$chengben,$chengben_price){
        if(empty($chengben) || empty($chengben_price)){         //没有成本价
            if(empty($peifang_ids)){
                $chengben = 0;
                $chegnben_price = 0;
            }
            $peifang = db('goods_peifang')->where('id','in',$peifang_ids)->field('chengben,chengben_price')->select();

            $chengben = array_sum(array_map(function($peifang){return $peifang['chengben'];}, $peifang));
            $chengben_price = array_sum(array_map(function($peifang){return $peifang['chengben_price'];}, $peifang));
            return ['chengben'=>$chengben,'chengben_price'=>$chengben_price];
        }else{
            return ['chengben'=>$chengben,'chengben_price'=>$chengben_price];
        }

    }


    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @Param   $address    收货地址
     */
    public function count_delivery_fee($address=''){
        $root = request()->domain();
        $config_arr = config('dada');
        $config_arr['url'] = "http://newopen.imdada.cn/api/order/queryDeliverFee";          //订单详情查询
        $dada_obj = new DadaOpenapi($config_arr);
        $data_arr['origin_id'] = build_order_no().cookie('store_id');
        $store = db('store')->alias('a')->join('ys_city b','a.city_code=b.code','LEFT')->where('a.id',cookie('store_id'))->field('a.*,b.dada_code')->find();            //门店信息
        $data_arr['shop_no'] = $store['dada'];           //门店编号
        $data_arr['city_code'] = $store['dada_code'];           //门店编号
        $data_arr['cargo_price'] = 0.01;           //订单金额
        $data_arr['is_prepay'] = 0;           //是否需要垫付，0否
        $data_arr['receiver_name'] = '一朵';           //是否需要垫付，0否
        $data_arr['receiver_address'] = $address;           //收货地址
        $data_arr['callback'] = $root.'/index.php/index/dada/count_delivery_fee';           //是否需要垫付，0否
        $data_arr['receiver_phone'] = '18757685769';           //是否需要垫付，0否
        $fee_info = $dada_obj->pre_count_delevety_fee($data_arr);          //与计算订单运费
        $result = json_decode($fee_info,true);
        if(empty($result)){
            return ['code'>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
        }else if($result['status'] =='fail' && $result['code'] != 0){
            return ['code'>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
//           $this->error('地址填写错误或不在配送范围，请检查并核实','');
        }

        $price = $this->getDeliveryFee($result['result']['distance']);

        return ['code'=>1,'msg'=>$price['msg']];

    }

    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @param $distance
     * @return array
     */
    private function getDeliveryFee($distance){
        $distance = $distance/2/500;
        //查询运费信息
        $data = Db::name('delivery_fee')->where('is_deleted',0)->order('distance asc')->select();
        foreach($data as $k => $v){
            if($distance < $v['distance']){
                return ['code'=>1,'msg'=>$v['price']];
                break;
            }
        }
        $val = end($data);
        return ['code'=>1,'msg'=>$val['price']];
    }

}